﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Linq;
using System.Xml;

namespace RefreshExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            var excel = new Application();
            //var da = excel.DisplayAlerts;
            excel.DisplayAlerts = false;

            try
            {
                var configFileName = args[0];

                var doc = new XmlDocument();
                doc.Load(configFileName);

                var root = doc.DocumentElement;

                var m = new XmlNamespaceManager(doc.Schemas.NameTable);
                m.AddNamespace(root.Prefix, root.NamespaceURI);

                //перебор по источникам
                var tasks = doc.SelectNodes("/my:myFields/my:workbook", m).Cast<XmlNode>();

                foreach (var task in tasks)
                {
                    Workbook wb = null;

                    var filePath = task.InnerText;// .SelectSingleNode("@my:fileName", m).FirstChild.Value;
                    var password = task.SelectSingleNode("@my:password", m).FirstChild.Value;

                    try
                    {
                        Console.WriteLine("{0}: Refresh {1}", DateTime.Now, filePath);
                        wb = excel.Workbooks.Open(filePath, WriteResPassword: password);
                        if (wb.ReadOnly) throw new Exception("Workbook is locked for editing by another user.");
                        wb.RefreshAll();
                        wb.Save();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("{0}: Ошибка:", DateTime.Now);
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (wb != null) wb.Close();
                        wb = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}: Error:", DateTime.Now);
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //excel.DisplayAlerts = da;
                excel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                excel = null;

                Console.WriteLine("{0}: Press any key...", DateTime.Now);
                Console.ReadKey();
            }
        }
    }
}
